﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NetPackage
{
    public class ByteArrayReader
    {
        public ByteArrayReader(System.IO.Stream stream,bool littleEndian)
        {
            LittleEndian = littleEndian;
            mReader = new System.IO.BinaryReader(stream);
        }   

        private System.IO.BinaryReader mReader;

        public bool LittleEndian
        {
            get;
            set;
        }

        public byte Read()
        {
            return mReader.ReadByte();
        }

        public bool ReadBool()
        {
            return mReader.ReadBoolean();
        }

        public short ReadShort()
        {
            short value = mReader.ReadInt16();
            if (!LittleEndian)
                value = Endian.SwapInt16(value);
            return value;

        }

        public int ReadInt()
        {
            int value = mReader.ReadInt32();
            if (!LittleEndian)
                value = Endian.SwapInt32(value);
            return value;
        }

        public long ReadLong()
        {
            long value = mReader.ReadInt64();
            if (!LittleEndian)
                value = Endian.SwapInt64(value);
            return value;
        }

        public ushort ReadUShort()
        {
            ushort value = mReader.ReadUInt16();
            if (!LittleEndian)
                value = Endian.SwapUInt16(value);
            return value;

        }

        public uint ReadUInt()
        {
            uint value = mReader.ReadUInt32();
            if (!LittleEndian)
                value = Endian.SwapUInt32(value);
            return value;
        }

        public ulong ReadULong()
        {
            ulong value = mReader.ReadUInt64();
            if (!LittleEndian)
                value = Endian.SwapUInt64(value);
            return value;
        }

        public char ReadChar()
        {
            return (char)this.ReadShort();
        }

        public unsafe float ReadFloat()
        {
            int num;
            num = this.ReadInt();
            return *(float*)(&num);
        }

        public unsafe double ReadDouble()
        {
            long num;
            num = this.ReadLong();
            return *(double*)(&num);
        }

        public string ReadUTF()
        {
            ushort value = ReadUShort();
            if (value > 0)
            {
                byte[] result = ReadBytes(value);
                return Encoding.UTF8.GetString(result);
            }
            return null;
        }

        public byte[] ReadBytes(int count)
        {
            byte[] result = mReader.ReadBytes(count);
            return result;
        }
       
    }
}
